<template>
  <!-- 业务组件配置管理 -->
  <BaseMainSlot :show-tab="true">
    <template v-slot:btn-box>
      <ActionBar :add-active="addActive" :del-active="delActive" :cancel-active="cancelActive" :has-edit="false" :has-del="false" :has-save="false" :has-add="true" :save-active="saveActive" @add="add" @cancel="cancel" @del="del" />
    </template>
    <template v-slot:search-box>
      <SearchBox @search="search">
        <div class="common-search-item">
          <div class="label">疾病名称:</div>
          <div class="input">
            <el-input v-model="diseaseName" placeholder="请输入疾病名称" clearable @input="search()" />
          </div>
        </div>
      </SearchBox>
    </template>
    <template v-slot:table-box>
      <!-- 业务组件展示表格 -->
      <div class="zh-table-view">
        <el-table :data="tableData" height="100%">
          <el-table-column type="index" label="序号" width="55" align="center" />
          <el-table-column prop="diseaseName" label="疾病名称" />
          <el-table-column prop="diagnosisItemSymbolNoList" label="诊断项症状编号" />
          <!-- <el-table-column label="诊断症状描述">
            <template slot-scope="scope">
              <div style="text-align: left;margin-bottom: 10px;font-size: 12px;" v-for="item, index in scope.row.diagnosisItemSymbolList" :key="index">{{ item }}</div>
            </template>
          </el-table-column> -->
          <el-table-column prop="mainSymptoms" label="特征描述">
            <template slot-scope="scope">{{ scope.row.mainSymptoms || '--' }}</template>
          </el-table-column>
          <el-table-column prop="preventionMethod" label="治疗方法">
            <template slot-scope="scope">{{ scope.row.preventionMethod || '--' }}</template>
          </el-table-column>
          <el-table-column prop="therapeuticMethod" label="预防方法">
            <template slot-scope="scope">{{ scope.row.therapeuticMethod || '--' }}</template>
          </el-table-column>
          <el-table-column label="操作">
            <template slot-scope="scope">
              <el-button size="mini" type="primary" @click="handleEdit(scope.row)">修改</el-button>
              <el-button size="mini" type="warning" @click="dellineallmes(scope.$index, scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <Pagination :page-size="pageSize" :current-page="currentPage" :total-size="totalSize" @changePageSize="changePageSize" @changeCurrentPage="changeCurrentPage" />
      </div>
    </template>

    <template v-slot:dialog>
      <!-- 新增业务组件的弹框 -->
      <el-dialog :title="titleText + '诊断项'" class="formData" :visible.sync="dialogFormVisible" width="40%" :before-close="() => { dialogFormVisible = false }">
        <el-form ref="formData" label-position="left" :model="formData" :rules="rules" class="el-form">
          <el-form-item label="疾病名称" prop="diseaseName" class="w100p">
            <el-input v-model="formData.diseaseName" clearable placeholder="请输入疾病名称" />
          </el-form-item>
          <el-form-item label="品种查询症状" class="w100p">
            <el-select class="w100p" v-model="formData.plantVarietyId" filterable clearable placeholder="请选择养殖品种" @change="handleChangePlantVariety">
              <el-option v-for="item, index in varietyList" :key="index" :label="item.plantVarietyName" :value="item.plantVarietyId"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="诊断项症状" prop="diagnosisItemSymbolNoList" class="w100p">
            <el-select class="w100p" filterable clearable v-model="formData.diagnosisItemSymbolNoList" placeholder="请选择诊断项症状" multiple @change="changePlantType($event)">
              <el-option v-show="diagnosisItemObj[item.diagnosisItemId]==formData.plantVarietyName||!formData.plantVarietyName"
               v-for="item of diagnosisItemSymptomList" :key="item.diagnosisItemSymbolNo" :value="item.diagnosisItemSymbolNo">
                <span class="ellipsis" :title="item.diagnosisItemSymbolDesc">
                  {{ '症状名称：' + diagnosisItemObj[item.diagnosisItemId] + item.diagnosisItemName || '' }}
                  {{ '（' + item.diagnosisItemSymbolNo || '' + '）：' }}
                  {{ item.diagnosisItemSymbolDesc || '' }}</span>
              </el-option>
              <el-option disabled :value="-1">到底了</el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="症状权重占比" class="w100p">
            <el-table border style="width: 100%;height:200px;color:#444;overflow-y:auto;" v-if="formData.diseaseBankSymbolList&&formData.diseaseBankSymbolList.length" :data="formData.diseaseBankSymbolList" height="250">
              <el-table-column type="index" label="序号" width="55" align="center" />
              <el-table-column prop="diagnosisItemName" label="诊断项名称" />
              <el-table-column prop="diagnosisItemSymbolNo" label="诊断项症状编号" />
              <el-table-column prop="diagnosisItemSymbolDesc" label="诊断项症状描述" />
              <el-table-column label="权重占比">
                <template slot-scope="scope">
                  <el-input min="1" type="number" @input="changeInput($event)" v-model="scope.row.ratio" placeholder="请输入内容"></el-input>
                </template>
              </el-table-column>
            </el-table>
          </el-form-item>
          <el-form-item label="当前权重总和" class="w100p">
            <el-input disabled v-model="formData.ratioSum" type="textarea" placeholder="权重总和需要累积100%" clearable :rows="2" />
          </el-form-item>
          <el-form-item label="特殊症状描述" class="w100p">
            <el-input v-model="formData.mainSymptoms" type="textarea" placeholder="请输入特殊症状描述" clearable :rows="2" />
          </el-form-item>
          <el-form-item label="预防方法" prop="preventionMethod" class="w100p">
            <el-input v-model="formData.preventionMethod" type="textarea" placeholder="请输入预防方法" clearable :rows="2" />
          </el-form-item>

          <el-form-item label="治疗方法" prop="therapeuticMethod" class="w100p">
            <el-input v-model="formData.therapeuticMethod" type="textarea" placeholder="请输入治疗方法" clearable :rows="2" />
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="cancel('formData')">取 消</el-button>
          <el-button type="primary" @click="savemes">保 存</el-button>
        </div>
      </el-dialog>
    </template>
  </BaseMainSlot>
</template>
<script>
import ActionBar from '@/components/ActionBar/index';
import { mymixin } from '@/utils/mixins';
import SearchBox from '@/components/SearchBox';
import BaseMainSlot from '@/components/BaseMainSlot/newBaseMainSlot.vue';
import zhreq from '@/api/basic-info-manage/disease-management';
import diagnosticItemManagement from '@/api/basic-info-manage/diagnosticItem-management';
import diagnosticItemSymptom from '@/api/basic-info-manage/diagnostic-item-symptom';
import varietyManagement from '@/api/basic-info-manage/breed-varieties-management';
import upload from '@/components/uploadimage/upload.vue';
import Pagination from '@/components/Pagination';
// import { getTitleList } from "@/components/getnameurl";
export default {
  components: { ActionBar, Pagination, BaseMainSlot, SearchBox, upload },
  mixins: [mymixin],
  data() {
    return {
      isshowuploadpic: false,
      dialogFormVisible: false,
      tableData: [],
      pageSize: 10,
      currentPage: 1,
      totalSize: 0,
      diseaseName: '',
      formData: {},
      titleText:'',
      diagnosisItemList: [],
      varietyList: [],
      diagnosisItemObj: {},
      diagnosisItemSymptomList: [],
      rules: {
        diseaseName: [{ required: true, message: '请输入', trigger: 'change' }],
        plantVarietyId: [{ required: true, message: '请选择', trigger: 'change' }],
        diagnosisItemSymbolNoList: [{ required: true, message: '请选择', trigger: 'change' }],
        therapeuticMethod: [{ required: true, message: '请输入', trigger: 'change' }],
        therapeuticMethod: [{ required: true, message: '请输入', trigger: 'change' }],
        preventionMethod: [{ required: true, message: '请输入', trigger: 'change' }]
      }
    };
  },
  created() {},
  mounted() {
    this.initData();
  },
  methods: {
    changePlantType(e) {
      this.formData.diseaseBankSymbolList = [];
      let list = JSON.parse(JSON.stringify(e));
      let newlist = [];
      list.forEach((item) => {
        this.diagnosisItemSymptomList.forEach((itemson) => {
          if (itemson.diagnosisItemSymbolNo == item) {
            this.$set(itemson, 'ratio', 10);
            newlist.push(itemson);
          }
        });
      });
      this.formData.diseaseBankSymbolList = newlist;
      this.changeInput(true);
      console.log(this.formData.diseaseBankSymbolList,e);
    },

    changeInput(e) {
      if (e) {
        console.log(this.formData);
        if (this.formData.diseaseBankSymbolList) {
          let list = JSON.parse(JSON.stringify(this.formData.diseaseBankSymbolList));
          console.log(list);
          let sum = 0;
          list.forEach((item) => {
            sum = Number(sum) + Number(item.ratio);
          });
        //   this.formData.ratioSum = sum;
          this.$set(this.formData,'ratioSum',sum)
        }
      }
    },
    // 获取下拉框信息
    async initData() {
      // let { data: varietyList } = await varietyManagement.queryByCondition({ farming: "FISH" });
      let { data: diagnosisItemList } = await diagnosticItemManagement.queryByCondition({});
      let { data: diagnosisItemSymptomList } = await diagnosticItemSymptom.queryByCondition({});
      let varietyList = [];
      this.diagnosisItemList = diagnosisItemList || [];
      this.diagnosisItemSymptomList = diagnosisItemSymptomList || [];
      this.diagnosisItemList.forEach((e) => {
        this.diagnosisItemObj[e.diagnosisItemId] = e.plantVarietyName;
        if (!varietyList.some((v) => v.plantVarietyId == e.plantVarietyId)) {
          varietyList.push(e);
        }
      });
      console.log(varietyList);
      this.varietyList = varietyList || [];
      this.gettabledataList();
    },
    // 获取表格信息
    gettabledataList() {
      let params = {
        page: this.currentPage,
        size: this.pageSize,
        entity: {
          diseaseName: this.diseaseName
        }
      };
      zhreq
        .queryPageByCondition(params)
        .then((res) => {
          let resData = res.data || {};
          if (res.code === 1) {
            this.tableData = resData.content || [];
            this.totalSize = resData.totalElements;
            this.resetActionBar();
          } else {
            this.$message.warning('获取表格失败');
          }
        })
        .catch((err) => {
          console.log(err);
        });
    },
    // 搜索
    search() {
      this.currentPage = 1;
      this.gettabledataList();
    },
    changePageSize(pageSize) {
      this.pageSize = pageSize;
      this.gettabledataList();
    },
    changeCurrentPage(currentPage) {
      this.currentPage = currentPage;
      this.gettabledataList();
    },
    // 删除一个业务组件
    dellineallmes(i, e) {
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          zhreq.delList([e.diseaseBankId]).then((res) => {
            if (res.code === 1) {
              this.$message.success('删除成功！');
              this.gettabledataList();
            } else {
              this.$message.success('删除失败！');
            }
          });
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });
        });
    },
    handleChangePlantVariety(id, clearDiseaseManegeList) {
      let rut = this.varietyList.find((e) => {
        return e.plantVarietyId == id;
      });
      let plantVarietyName = rut?.plantVarietyName || '';
      this.$set(this.formData, 'plantVarietyName', plantVarietyName);
      console.log(plantVarietyName);
      // this.diagnosisItemSymptomList = []
      // if (!rut) {
      //     this.$message.warning('该疾病数据关联的品种被删除或未启用，请重新关联品种！')
      // }
      // !clearDiseaseManegeList && (this.$set(this.formData, 'diagnosisItemSymbolNoList', []))
      // zhreq.findByPlantVarietyId(id).then(res => {
      //     if (res.code == 1 && res.data.length > 0) {
      //         this.diagnosisItemSymptomList = res.data || [];
      //     } else {
      //         this.$message.warning('未获取到关联品种的诊断项！')
      //     }

      // }).catch(err => {
      //     console.log(err)
      //     this.$message.warning('未获取到关联品种的诊断项！')
      // })
    },
    handleEdit(row) {
      if (row) {
        this.formData = JSON.parse(JSON.stringify(row));
        console.log(row,'row');
        let newdiseaseBankSymbolList =[]
        row.diseaseBankSymbolList.forEach(item=>{
          this.diagnosisItemSymptomList.forEach(itemson=>{
            if(item.diagnosisItemSymbolNo==itemson.diagnosisItemSymbolNo){
              let obj = {
                ...item,
                diagnosisItemName:itemson.diagnosisItemName,
                diagnosisItemSymbolDesc:itemson.diagnosisItemSymbolDesc
              }
              newdiseaseBankSymbolList.push(obj)
            }
          })
        })
        delete this.formData.diseaseBankSymbolList

        this.formData = {
          ...this.formData,
          diseaseBankSymbolList:newdiseaseBankSymbolList,
          diagnosisItemSymbolNoList: this.formData.diagnosisItemSymbolNoList?.split(',').map(item=>{
            return item.split(/[\t\r\f\n\s]*/g).join(''); 
          })
        };
        console.log(' this.formData', this.formData);
        this.changeInput(true);
        this.nowChanceStau = 'edit';
        this.titleText = "修改"
        this.dialogFormVisible = true;
        setTimeout(() => {
          this.handleChangePlantVariety(row.plantVarietyId, true);
        }, 500);
      } else {
        this.nowChanceStau = 'add';
      }
    },
    // 保存要添加的业务的组件信息
    savemes() {
      this.$refs['formData'].validate((valid) => {
        if (valid) {
          if (this.formData.ratioSum == 100) {
            let params = {
              ...this.formData,
              diagnosisItemSymbolNoList: this.formData.diagnosisItemSymbolNoList.toString()
            };
            if (this.nowChanceStau === 'edit') {
              let param = {
                ...this.formData,
                diagnosisItemSymbolNoList: this.formData.diagnosisItemSymbolNoList.toString()
              };
              zhreq.edit(param).then((response) => {
                let mes = response;
                if (mes.code === 1) {
                  this.$message.success('修改成功！');
                  this.gettabledataList();
                  this.cancel('formData');
                } else {
                  this.$message.warning(res.msg || '修改成功！');
                }
              });
            } else if (this.nowChanceStau === 'add') {
              let param = {
                ...this.formData,
                diagnosisItemSymbolNoList: this.formData.diagnosisItemSymbolNoList.toString()
              };
              zhreq.add(param).then((response) => {
                let mes = response;
                if (mes.code === 1) {
                  this.$message.success('添加成功！');
                  this.gettabledataList();
                  this.cancel('formData');
                } else {
                  this.$message.warning(mes.msg || '操作失败！');
                }
              });
            }
          } else {
            this.$message.warning('当前权重总和需要等于100');
          }
        } else {
          return false;
        }
      });
    }
  }
};
</script>

<style lang="scss" scoped>
@import '~@/styles/variables.scss';

.imageStyle {
  height: 100px;
  width: 100px;
  border-radius: 4px;
}
</style>